<?php 
session_start();
include "../_init_.php";
include(constant('PATH_INCLUDE').'/class.uploadhelper.php');

$MAX_IMAGE_NUMBER = 10;

$dtEqu = new DataTable(constant('DB_TABLE_EQUIPMENT'));
$dtFur = new DataTable(constant('DB_TABLE_FURNITURE'));
$dtRentType = new DataTable(constant('DB_TABLE_RENT_TYPE'));

$equ_list = $dtEqu->get_list('','sn');
$fur_list = $dtFur->get_list('','sn');
$renttype_list = $dtRentType->get_list('','sn');

$dtRent = new DataTable(constant('DB_TABLE_RENT'));
//增加数据
$action= isset($_REQUEST["action"])?$_REQUEST["action"]:'';
switch($action)
{
	case 'edit':
		$info = $dtRent->get($_REQUEST['id']);
	break;
	case 'save':
		$data = $_REQUEST;
		try
		{
			$is_new = true;
			$data = checkData($data);
			if(isset($data['id']) && intval($data['id']) > 0)
				$is_new = false;
			$data = $dtRent->save($data);
			$rentID = $data['id'];
			 process_image_gallery($rentID);
			ob_clean();
			header("Location:rent_list.php");
			exit();
		}catch(Exception $ex)
		{
			$action = 'edit';
			$info = $data;
			$error_message = $ex->getMessage();
		}
	break;
	case 'new':
		$info = array();
	break;
}

function checkData($data)
{
	global $dtRent;
	if(strlen($data['title']) == 0)
		throw new Exception("請输入標題!");
		
	
	//upload image
	try
	{
		$uploadDir = '/upload/';
		$path = UploadHelper::uploadImage('image',$uploadDir);
		$data['image'] = $path;
		
		//delete exist image
		$old_data = $dtRent->get($data['id']);
		if($old_data)
		{
			$img_path = constant('SITE_WEB_DISK_DIR').$old_data['image'];
			if(file_exists($img_path))
			@unlink($img_path);
		}
	}catch(Exception $ex)
	{
	}
	
	//upload front image
	try
	{
		$uploadDir = '/upload/';
		$path = UploadHelper::uploadImage('image1',$uploadDir);
		$data['image1'] = $path;
		
		//delete exist image
		$old_data = $dtRent->get($data['id']);
		if($old_data)
		{
			$img_path = constant('SITE_WEB_DISK_DIR').$old_data['image1'];
			if(file_exists($img_path))
			@unlink($img_path);
		}
	}catch(Exception $ex)
	{
	}
	$data['equipment'] = $data['equipment']?implode(',',$data['equipment']):'';
	$data['furniture'] = $data['furniture']?implode(',',$data['furniture']):'';
	$data['type'] = $data['type']?implode(',',$data['type']):'';
	return $data;
}

function process_image_gallery($rentID)
{
	global $MAX_IMAGE_NUMBER;
	$dtRentImage = new DataTable(constant('DB_TABLE_RENT_IMAGE'));
	//delete images
	$sn_list = $_REQUEST['imagegallerydelete'];
	if($sn_list)
	{
		foreach($sn_list as $sn)
		{
		
        	$condition = sprintf("`rId`=%d AND `sn`=%d",$rentID,$sn);
       		$data_row = $dtRentImage->get_row($condition);
       		if($data_row)
       		{
       			$dtRentImage->remove($data_row['id']);
       			$img_path = constant('SITE_WEB_DISK_DIR').$data_row['image'];
				if(file_exists($img_path))
					@unlink($img_path);
       		}
       	}
	}
	
	//insert or update image
	for($i=0;$i<$MAX_IMAGE_NUMBER;$i++)
	{
		try
		{
		$uploadDir = '/upload/';
		$path = UploadHelper::uploadImage('imagegallery_'.$i,$uploadDir);
		$condition = sprintf("`rId`=%d AND `sn`=%d",$rentID,$i);
       	$data_row = $dtRentImage->get_row($condition);
		if(	$data_row == null)
		{
			$data_row = array('rId'=>$rentID,'sn'=>$i);
		}
		$data_row['image'] = $path;
		 $dtRentImage->save($data_row);
		}catch(Exception $ex)
		{
		}
	}
	
}
?>
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>網站管理系統</title>


<LINK REL="stylesheet" HREF="css/style.css" TYPE="text/css">
<LINK REL="stylesheet" HREF="css/main.css" TYPE="text/css">
<script src="js/FancyZoom.js" language="JavaScript" type="text/javascript"></script>
<script src="js/FancyZoomHTML.js" language="JavaScript" type="text/javascript"></script>
<script src="../js/jquery-ui-1.7.3.custom/js/jquery-1.3.2.min.js" language="JavaScript" type="text/javascript"></script>
<script language="javascript">
$(function(){
	var equ_id_list = '<?php echo $info['equipment'];?>';
	var fur_id_list = '<?php echo $info['furniture'];?>';
	var renttype_id_list = '<?php echo $info['type'];?>';
	
	equ_id_list = equ_id_list.split(',');
	fur_id_list = fur_id_list.split(',');
	renttype_id_list = renttype_id_list.split(',');
	
	$.each(equ_id_list,function(i,v){
		$("input[name='equipment[]'][value='"+v+"']").attr('checked','checked');
	});
	$.each(fur_id_list,function(i,v){
		$("input[name='furniture[]'][value='"+v+"']").attr('checked','checked');
	});
	
	$.each(renttype_id_list,function(i,v){
		$("input[name='type[]'][value='"+v+"']").attr('checked','checked');
	});
});

</script>
<style>
.chec
{
	width:20px;
}
.btn
{
	width:70px;
}
</style>
<body onLoad="setupZoom();">
<table width="98%" border="0" class="table2">
  <tr>
    <td>房源管理 - 房源</td>
  </tr>
</table>
<?php if($error_message):?>
<div class="error_message"><?php echo $error_message;?></div>
<?php endif;?>
<?php if($sucess_message):?>
<div class="success_message"><?php echo $sucess_message;?></div>
<?php endif;?>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
  <tr> 
    <td width="100%" align="center" valign="top">
      </strong> 
      <table  width="100%" border="0" cellpadding="2" cellspacing="1" class="table_southidc">
        <tr class="tr_southidc"> 
          <FORM  method="post" name="form1"  onsubmit="return check(this);" enctype="multipart/form-data" >	
          <input type="hidden" name="action" value="save"/>
          <input type="hidden" name="id" value="<?php echo $info['id'];?>"/>
            <td bgcolor="#B0DAFF"><table width="100%" border="0" align="center" cellspacing="1" >
                <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">內頁顯示圖片：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="image" type="file"  size="15" maxlength="20">
                  <?php if($info['image']):?>
                  <image src="<?php echo constant('SITE_URL_PATH').$info['image'];?>" width="40" height="40"/>
                  <?php endif;?>
                  </td>
                </tr>
                <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">首頁最新圖片：</div></td>
                  <td width="87%" bgcolor="#FFFFFF">
                  <input name="image1" type="file"  size="15" maxlength="20">
                   <?php if($info['image1']):?>
                  <image src="<?php echo constant('SITE_URL_PATH').$info['image1'];?>" width="40" height="40"/>
                    <?php endif;?>
                  </td>
                </tr>
                <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">標題：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="title" type="text"  size="15" maxlength="20" value="<?php echo $info['title'];?>"></td>
                </tr>			
                <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">類型：</div></td>
                  <td width="87%" bgcolor="#FFFFFF">
                  <?php foreach($renttype_list as $tmpData):?>
                  <input class="chec" type="checkbox" name="type[]" value="<?php echo $tmpData['id'];?>"/><?php echo $tmpData['name'];?>
                  <?php endforeach;?>
                  </td>
                </tr>	
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">坪數：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="size" type="text"  size="15" maxlength="20" value="<?php echo $info['size'];?>"></td>
                </tr>	
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">租金：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="cost" type="text"  size="15" maxlength="20" value="<?php echo $info['cost'];?>"></td>
                </tr>	
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">押金：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="pre_cost" type="text"  size="15" maxlength="20" value="<?php echo $info['pre_cost'];?>"></td>
                </tr>	
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">格局：</div></td>
                  <td width="87%" bgcolor="#FFFFFF">
                 
                  <input name="style1" type="text"  size="3" maxlength="20" value="<?php echo $info['style1'];?>" style="width:40px;">&nbsp;房&nbsp;&nbsp;
                  <input name="style2" type="text"  size="3" maxlength="20" value="<?php echo $info['style2'];?>" style="width:40px;">&nbsp;廳&nbsp;&nbsp;
                 <input name="style3" type="text"  size="3" maxlength="20" value="<?php echo $info['style3'];?>" style="width:40px;">&nbsp;衛&nbsp;&nbsp;
                 <input name="style4" type="text"  size="3" maxlength="20" value="<?php echo $info['style4'];?>" style="width:40px;">&nbsp;廚&nbsp;&nbsp;
         
                  </td>
                </tr>	
				 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">房屋地點：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="address" type="text"  size="15" maxlength="20" value="<?php echo $info['address'];?>"></td>
                </tr>
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">樓别/樓高：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="height" type="text"  size="15" maxlength="20" value="<?php echo $info['height'];?>"></td>
                </tr>
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">車位：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input type="text" name="garage"   size="15" maxlength="20" value="<?php echo $info['garage'];?>"></td>
                </tr>
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">排序：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="sn" type="text"  size="15" maxlength="20" value="<?php echo $info['sn'];?>"></td>
                </tr>
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">家電：</div></td>
                  <td width="87%" bgcolor="#FFFFFF">
                  <?php foreach($equ_list as $tmpData):?>
                  <input class="chec" type="checkbox" name="equipment[]" value="<?php echo $tmpData['id'];?>"/><?php echo $tmpData['name'];?>
                  <?php endforeach;?>
                  </td>
                </tr>
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">家具：</div></td>
                  <td width="87%" bgcolor="#FFFFFF">
                  <?php foreach($fur_list as $tmpData):?>
                  <input class="chec" type="checkbox" name="furniture[]" value="<?php echo $tmpData['id'];?>"/><?php echo $tmpData['name'];?>
                  <?php endforeach;?>
                  </td>
                </tr>
                 <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">特色說明：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><textarea name="description" cols="50" rows="4"><?php echo $info['description'];?></textarea></td>
                </tr>
                <?php
                $imgList = array();
                if($info['id'])
                {
                	$dtRentImage = new DataTable(constant('DB_TABLE_RENT_IMAGE'));
               		$condition = sprintf("`rId`=%d",$info['id']);
       	  			$data_list = $dtRentImage->get_list($condition,'sn');
       	  			
       	  			foreach($data_list as $rowData)
       	  			{
       	  				$imgList[$rowData['sn']] = $rowData['image'];
       	  			}
       	  		}
                ?>
                <?php for($i=0;$i<$MAX_IMAGE_NUMBER;$i++):?>
                <tr> 
                  <td width="13%" height="22" bgcolor="#FFFFFF"> <div align="right">圖片<?php echo $i+1;?>：</div></td>
                  <td width="87%" bgcolor="#FFFFFF"><input name="imagegallery_<?php echo $i;?>" type="file"  size="15" maxlength="20">
                  <?php if(array_key_exists($i,$imgList)):?>
                  <image src="<?php echo constant('SITE_URL_PATH').$imgList[$i];?>" width="40" height="40"/><input type="checkbox" name="imagegallerydelete[]" value="<?php echo $i;?>"/>刪除
                  <?php endif;?>
                  </td>
                </tr>
                <?php endfor;?>
                <tr> 
                  <td height="22" colspan="2" bgcolor="#FFFFFF"><div align="center">
                      
                      <INPUT type=submit    name=Submit2 value="保存" class="btn"/>
                  </div></td>
                </tr>
            </table></td>
          </form>
        </tr>
      </table>
    </td>
</tr>
</table>
</body>
</html>